package com.projektio.io;

public class MatrixFilter extends Filter 
{
	private int scale;
	//private int offset;
	private int[][] filter;
	
	public MatrixFilter()
	{
		this.scale = 1; 
		//this.offset = 0;
		this.filter = new int[][]{{0,0,0},{0,1,0},{0,0,0}};
	}
	
	public MatrixFilter(int[][] filter)
	{
		setFilter(filter, 1);//, 0);
	}
	
	public MatrixFilter(int[][] filter, int scale)//, int offset)
	{
		setFilter(filter, scale);//, offset);
	}
	
	public void setFilter(int[][] filter)
	{
		setFilter(filter, 1);//, 0);
	}
	
	public void setFilter(int[][] filter, int scale)//, int offset)
	{
		if(filter.length != filter[0].length) throw new IllegalArgumentException("Not a square filter table!");
		if(filter.length % 2 == 0) throw new IllegalArgumentException("Filter table can't be even!");
		this.scale = scale; 
		//this.offset = 0;
		this.filter = filter;
	}
	
	public Image doFiltering(Image image) 
	{
		Image temp = new Image(image);
		int size = filter.length / 2;
		
		for(int i = size; i < image.getHeight() - size ; i++)
		{
			for(int j = size; j < image.getWidth() - size; j++)
			{
				short[] value = new short[image.getPixel(0, 0).length];
				for(int m = -size; m <= size; m++)
				{
					for(int n = -size; n <= size; n++)
					{
						short[] color = image.getPixel(j+n, i+m);
						for(int k = 0; k < color.length; k++)
							value[k] += color[k]*filter[m+size][n+size];
					}
				}
				for(int k = 0; k < value.length; k++) value[k] /= scale;
				temp.setPixel(j, i, value);
			}
		}
		
		return temp;//*/
	}
	
}
